﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.InvDoc.TransferForm;
using UFIDA.U9.ISV.TransferFormISV.Proxy;
using UFIDA.U9.ISV.TransferFormISV;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.InvDoc.Enums;
using UFIDA.U9.CBO.SCM.Item;

namespace ufida.u9.ait.openapi
{
    internal class TransferFormBase
    {
        /// <summary>
        /// 预处理
        /// </summary>
        /// <param name="dto"></param>
        private static void preSave(IC_TransferFormDTOData dto)
        {
            //为了自动生成单号,清空传入单号
            dto.DocNo = "";

            foreach (IC_TransferFormLDTOData linedto in dto.TransferFormLine)
            {
                if (String.IsNullOrEmpty(linedto.ItemInfo?.ItemCode)) throw new Exception("料品[ItemInfo]为空");
                if (String.IsNullOrEmpty(linedto.Wh?.Code)) throw new Exception("仓库[Wh]为空");
                if (linedto.StoreUOMQty <= 0) throw new Exception("数量[StoreUOMQty]为空");

                //转换前
                //货位处理
                if (linedto.BinInfo != null)
                {
                    UFIDA.U9.CBO.SCM.Bin.Bin bin = EntityUtils.GetEntityByPath<UFIDA.U9.CBO.SCM.Bin.Bin>($"Code='{linedto.BinInfo.Code}' and Warehouse.Code='{linedto.Wh.Code}'");
                    linedto.BinInfo.Bin = bin.ID;
                }
                //双单位处理
                if (linedto.CostUOMQty > 0)
                {
                    linedto.SUToCURate = linedto.CostUOMQty / linedto.StoreUOMQty;//库存-成本
                    /**
                     * 因为标准代码中固定查询了转换率,需要自动生成组间转换率
                     * 代码 
                     * UFIDA.U9.InvDoc.InvDocBE.dll
                     * UFIDA.U9.InvDoc.TransferForm.TransferForm
                     * 方法
                     * SetLineDefaultValue中固定调用CalUOMRateBPProxy
                     */
                    ItemMaster item = EntityUtils.GetEntityByCode<ItemMaster>(linedto.ItemInfo.ItemCode);
                    ItemConvertRatioAITDTOData dto1 = new ItemConvertRatioAITDTOData()
                    {
                        ItemMaster = new CopyOfCommonArchiveDataDTOData() { Code = item.Code },
                        FromUOM = new CopyOfCommonArchiveDataDTOData { Code = item.InventorySecondUOM.Code },
                        ToUOM = new CopyOfCommonArchiveDataDTOData { Code = item.CostUOM.Code },
                        Ratio=linedto.SUToCURate,
                    };
                    ItemConvertRatioSaveSV sv = new ItemConvertRatioSaveSV();
                    sv.Data = new List<ItemConvertRatioAITDTOData> { dto1 };
                    sv.Do();
                }
                

                //转换后
                foreach (IC_TransferFormSLDTOData sublinedto in linedto.TransferFormSubLine)
                {
                    if (sublinedto.ItemInfo?.ItemCode == null)
                        throw new Exception("必须传入料品[ItemInfo]");
                    if (sublinedto.Wh?.Code == null)
                        throw new Exception("必须传入仓库[Wh]");

                    //货位处理
                    if (sublinedto.BinInfo != null)
                    {
                        UFIDA.U9.CBO.SCM.Bin.Bin bin = EntityUtils.GetEntityByPath<UFIDA.U9.CBO.SCM.Bin.Bin>($"Code='{sublinedto.BinInfo.Code}' and Warehouse.Code='{sublinedto.Wh.Code}'");
                        sublinedto.BinInfo.Bin = bin.ID;
                    }

                    //批号处理
                    if(sublinedto.LotInfo?.LotCode != null&& sublinedto.LotInfo?.DisabledDatetime>DateTime.MinValue)
                    {
                        //批号有失效日期时的特殊处理
                        UFIDA.U9.Lot.LotMaster lotMaster = LotMasterBase.SaveEntity(sublinedto.LotInfo.LotCode, sublinedto.ItemInfo.ItemCode, sublinedto.LotInfo);
                        sublinedto.LotInfo.LotMaster = lotMaster.ID;
                    }

                    //双单位处理
                    if (sublinedto.CostUOMQty > 0 && sublinedto.StoreUOMQty>0)
                    {
                        sublinedto.SUToCURate = sublinedto.CostUOMQty / sublinedto.StoreUOMQty;//库存-成本
                    }
                }
            }
        }

        public static TransferForm CreateDoc(CopyOfIC_TransferFormDTOData dto)
        {
            IC_TransferFormDTOData dto1 = new IC_TransferFormDTOData();
            DTOUtils.DTOPropCopy(dto, dto1);
            if (dto.DescFlexField != null)
            {
                //扩展字段特殊处理
                //形态转换BE扩展字段名DescFlexField,但是DTO的扩展字段名为DescFlexSegments
                dto1.DescFlexSegments = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegmentsData();
                DTOUtils.DTOPropCopy(dto.DescFlexField, dto1.DescFlexSegments);
            }
            preSave(dto1);
            //生产,调用产业链服务
            CommonCreateTransferFormSRVProxy proxy = new CommonCreateTransferFormSRVProxy();
            proxy.TransferFormDTOList = new List<IC_TransferFormDTOData> { dto1 };
            List<CommonArchiveDataDTOData> ret = proxy.Do();
            //处理返回
            TransferForm doc = TransferForm.Finder.FindByID(ret[0].ID);
            if (doc == null)
                throw new Exception("单号查找失败!");
            return doc;
        }

        public static TransferForm ApproveDoc(TransferForm doc)
        {
            if (doc.Status == INVDocStatus.Approved)
                throw new Exception($"单号:[{doc.DocNo}]状态为审核");

            if (doc.Status== INVDocStatus.Open)
            {
                CommitDoc(doc);
                doc = doc.Key.GetEntity();
            }
            CommonApprovedTransferFormSRV sv = new CommonApprovedTransferFormSRV();
            sv.QueryList=new List<CommonArchiveDataDTO> { new CommonArchiveDataDTO { ID = doc.ID } };
            sv.Do();
            return doc;
        }

        public static TransferForm CommitDoc(TransferForm doc)
        {
            if (doc.Status != INVDocStatus.Open) 
                throw new Exception($"单号:[{doc.DocNo}]状态不为开立");
            CommonCommitTransferFormSRV sv = new CommonCommitTransferFormSRV();
            sv.QueryList = new List<CommonArchiveDataDTO> { new CommonArchiveDataDTO { ID = doc.ID } };
            sv.Do();

            return doc;
        }
    }
}
